//
// Copyright (c) 2009-2011, chunquedong
//
// This file is part of ChunMap project
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
//
// History:
//   2011-05-03  Jed Young  Creation
//

using chunmapView
using fwt
using gfx
using gfx2
using gfx2Imp

**
** MapCanvas is a map widget
**
@Js
class MapCanvas : Canvas2
{
  CMap map := CMap(Size(50, 50))
  private Image2? bufferImage

  OperateManager operateManager := OperateManager(this)
  CommandStack stack := CommandStack()

//////////////////////////////////////////////////////////////////////////
// paint
//////////////////////////////////////////////////////////////////////////

  override Void onPaint2(Graphics2 g)
  {
    if (resetSize || bufferImage == null) { renderMap; return }

    g.drawImage2(bufferImage, 0, 0)
    g.drawText("ChunMap", 2, 8)
  }

  private Bool resetSize()
  {
    if (size.w != map.view.width || size.h != map.view.height)
    {
      map.resetSize(size, size.w /2 , size.h /2)
      bufferImage = Image2(size)
      Env.cur.gc
      return true
    }
    return false
  }

  Void renderMap()
  {
    map.render
    g := bufferImage.graphics
    drawOriginImage(g, 0, 0)
    g.dispose
    repaint
  }

  Void drawOriginImage(Graphics2 g, Int dx, Int dy)
  {
    g.drawImage2(map.image, dx-map.xBuffer, dy-map.yBuffer)
  }

  Void paintOnBuffer(|Graphics2 g| f)
  {
    g := bufferImage.graphics
    g.fillRect(0, 0, bufferImage.size.w, bufferImage.size.h)
    f(g)
    g.dispose
  }

//////////////////////////////////////////////////////////////////////////
// getter
//////////////////////////////////////////////////////////////////////////

  ViewPort view() { map.view }

  LayerList layers() { map.layers }

//////////////////////////////////////////////////////////////////////////
// proxy
//////////////////////////////////////////////////////////////////////////

  This fullView() { map.fullView; return this }

  Void setCurrentTool(Tool plug) { operateManager.currentTool = plug }
  Void executeCommand(Command cmd) { operateManager.executeCommand(cmd) }
  Void undo() { operateManager.undo }
  Void redo() { operateManager.redo }
}

